<?php

namespace app\index\controller;
use app\commons\model\UserCard;
use think\exception\ValidateException;

class Crads
{
    /**
     * 领取列表
     */
    public function index(UserCard $userCard){
        $data = request()->param();
        $id = $data['id'] ?? 0;
        if(!$id) throw new ValidateException('参数错误！');
        $sale = \app\commons\model\Sale::where(['id'=>$id,'member_id'=>session('merch')])->value('id');
        if(!$sale) throw new ValidateException('只能操作当前商户相关信息！');
        $list = $userCard->where(['sale_id'=>$id])->order('id desc')->field(['user_id','id','sale_id','createtime','code','status'])->with(['member'])->paginate(10,false,['query'=>request()->param()]);
        return jsonp($list);
    }

    /**
     * 商家后台核销优惠券
     */
    public function writes(UserCard $userCard){
        $data = request()->param();
        $id = $data['id'] ?? 0;
        if(!$id) throw new ValidateException('参数错误！');
        $userCardInfo = $userCard->where(['id'=>$id])->field(['sale_id'])->find();
        if(!$userCardInfo) throw new ValidateException('卡券不存在！');
        $sale = \app\commons\model\Sale::where(['id'=>$userCardInfo['sale_id'],'member_id'=>session('merch')])->value('id');
        if(!$sale) throw new ValidateException('只能操作当前商户相关信息！');
        //核销 卡券
        $res = UserCard::where(['id'=>$id])->update(['status'=>1]);
        if(!$res) throw new ValidateException('核销失败！');
        return jsonp([]);
    }
}